<?php

namespace api\modules\v1\models\user;

use api\modules\v1\models\Common;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\Patterns;
use common\models\sms\SMS;
use common\models\Status;
use common\services\SMS\SmsAli;
use common\utils\CodeImgGenerate;
use Yii;
use yii\base\Exception;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class UserSms extends \api\modules\common\models\User
{

    public $user;
    public $phone;          // 手机号
    public $codeType;          // 不同模式
    public $img_code;          // 图形验证码

    /**
     * 验证规则
     */
    public function rules()
    {
        return [
            #发送注册验证码
            [['login_name','img_code'], 'required','message' => '{attribute}不能为空','on' => 'registerCode'],
            [['login_name'],'match','pattern' => Patterns::phoneNumber(),'message' => '手机号码格式不正确','on' => ['registerCode']],
            ['login_name', 'validateCodePhone', 'on' => 'registerCode'],
            ['img_code', "codeVerify", "on" => "registerCode"],

            #登录验证码
            [['login_name'], 'required','message' => '{attribute}不能为空','on' => 'loginCode'],
            [['login_name'],'match','pattern' => Patterns::phoneNumber(),'message' => '手机号码格式不正确','on' => ['loginCode']],
            ['login_name', 'validateCodePhone', 'on' => 'loginCode'],

            #忘记密码验证码
            [['login_name'], 'required','message' => '{attribute}不能为空','on' => ['forgetPasswordCode']],
            [['login_name'],'match','pattern' => Patterns::phoneNumber(),'message' => '手机号码格式不正确','on' => ['forgetPasswordCode']],
            ['login_name', 'validateCodePhone', 'on' => ['forgetPasswordCode']],

            #需改密码
            ['login_name', 'validateCodePhone', 'on' => ['forgetPasswordCode']],

            #设置和修改支付密码
            ['login_name', 'validateCodePhone', 'on' => ['payPasswordCode']],

            # 校验异地登录
            ['login_name', 'validateCodePhone', 'on' => ['verifyPlaceCode']],

            # 钱包开关验证码
            ['login_name', 'validateCodePhone', 'on' => ['moneySwitchCode']],

        ];
    }

    /**
     * 设置属性名称
     * @return array
     */
    public function attributeLabels() {
        return [
            'login_name' => '账号',
            'img_code' => '图形验证码',
        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios() {
        $newScenarios =  [
            'registerCode' => ['login_name','img_code'],
            'loginCode' => ['login_name',],
            'forgetPasswordCode' => ['login_name'],
            'modifyPasswordCode' => ['login_name'],
            'payPasswordCode' => ['login_name'],
            'verifyPlaceCode' => ['login_name'],
            'moneySwitchCode' => ['login_name'],

        ];
        return array_merge(parent::scenarios(), $newScenarios);
    }

    /**
     * 图像验证码
     */
    public function codeVerify($attribute)
    {
        if (!$this->hasErrors()) {
            $check = (new CodeImgGenerate()) -> check($this->img_code);
            if (!$check) {
                $this->addError($attribute, '图形验证码错误.');
            }
        }
    }

    //验证账号
    public function validateCodePhone($attribute) {
        if (!$this->hasErrors()) {
            $currentScenario = $this->scenario;
            switch ($currentScenario) {
                case 'registerCode':
                    $this->codeType = CacheKeys::CACHE_CODE_TYPE_REGISTER_CODE;
                    $this->phone = $this->login_name;
                    $andWhere[] = ['OR',['login_name' => $this->login_name],['phone' => $this->login_name]];
                    $this->user = static::getByAndWhere([],$andWhere);
                    if (!empty($this->user)) {
                        $this->addError($attribute, '该手机号已被注册.');
                    }
                    break;

                case 'loginCode':
                    $this->codeType = CacheKeys::CACHE_CODE_TYPE_LOGIN;
                    $this->phone = $this->login_name;
                    $andWhere[] = ['OR',['login_name' => $this->login_name],['phone' => $this->login_name]];
                    $this->user = static::getByAndWhere([],$andWhere);
                    if (empty($this->user)) {
                        $this->addError($attribute, '该手机未注册,请先注册.');
                    }

                    if ($this->user['is_login_by_code'] == Status::COMMON_RADIO_NO) {
                        $this->addError($attribute, '您已关闭验证码登录！');
                    }
                    break;

                case 'forgetPasswordCode':
                    $this->codeType = CacheKeys::CACHE_CODE_TYPE_FORGET_CODE;
                    $this->phone = $this->login_name;
                    $andWhere[] = ['OR',['login_name' => $this->login_name],['phone' => $this->login_name]];
                    $this->user = static::getByAndWhere([],$andWhere);
                    if (empty($this->user)) {
                        $this->addError($attribute, '账号不存在.');
                    }
                    break;

//                case 'modifyPasswordCode':
//                    $this->codeType = CacheKeys::CACHE_CODE_TYPE_MODIFY_PASSWORD_PHONE;
//                    $this->user = Yii::$app->getUser()->getIdentity();
//                    $this->phone = $this->user->phone;
//                    break;

                case 'payPasswordCode':
                    $this->codeType = CacheKeys::CACHE_CODE_TYPE_RESET_PAY_PASS_CODE;
                    $this->user = Yii::$app->getUser()->getIdentity();
                    $this->phone = $this->user->phone;
                    break;

                case 'verifyPlaceCode':
                    $this->codeType = CacheKeys::CACHE_CODE_TYPE_PLACE_PHONE;
                    $this->user = Yii::$app->getUser()->getIdentity();
                    if ($this->user) {
                        $this->phone = $this->user->phone;
                    } else {
                        $this->phone = $this->login_name;
                    }
                    break;

//                case 'moneySwitchCode':
//                    $this->codeType = CacheKeys::CACHE_CODE_TYPE_MONEY_SWITCH_CODE;
//                    $this->user = Yii::$app->getUser()->getIdentity();
//                    $this->phone = $this->user->phone;
//                    break;
            }
        }
    }


    /**
     * 【发送验证码】通用
     * @return array
     */
    public function sendPhoneCode() {
        try {

            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            if ($this->scenario == "payPasswordCode") {
                $this->codeType = CacheKeys::CACHE_CODE_TYPE_RESET_PAY_PASS_CODE;
                $this->user = Yii::$app->getUser()->getIdentity();
                $this->phone = $this->user->phone;
            }

            if ($this->scenario == "moneySwitchCode") {
                $this->codeType = CacheKeys::CACHE_CODE_TYPE_MONEY_SWITCH_CODE;
                $this->user = Yii::$app->getUser()->getIdentity();
                $this->phone = $this->user->phone;
            }

            if ($this->scenario == "modifyPasswordCode") {
                $this->codeType = CacheKeys::CACHE_CODE_TYPE_MODIFY_PASSWORD_PHONE;
                $this->user = Yii::$app->getUser()->getIdentity();
                $this->phone = $this->user->phone;
            }

            $res = (new SmsAli())->sendCode($this->phone, $this->codeType);
            if ($res['code'] != 1000) {
                throw new Exception($res['message']);
            }

            return Functions::formatRestAPI(0, '发送成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
